package com.xinda.xiaoxing.config.opc;

import com.xinda.xiaoxing.service.OPCService;
import org.openscada.opc.lib.da.Item;
import org.openscada.opc.lib.da.ServerConnectionStateListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Map;

public class ConnectionListener implements ServerConnectionStateListener,Connector{
    Logger logger = LoggerFactory.getLogger(ConnectionListener.class);

    Map<String, Item> idItemMap;
    String prefix;
    private boolean isConnected;
    String serverName;
    @Autowired
    OPCService opcService;

    @Override
    public void connectionStateChanged(boolean b) {
        if (b) {
            isConnected = true;
            logger.info("["+serverName+"]已连接！");
            //初始化设备
            logger.info("["+serverName+"]初始化点位");

            idItemMap.putAll(opcService.initItems(serverName,prefix));
        } else {
            isConnected = false;
            logger.error("["+serverName+"]连接断开!");
        }
    }

    public void setIdItemMap(Map<String, Item> idItemMap) {
        this.idItemMap = idItemMap;
    }

    public void setPrefix(String prefix) {
        this.prefix = prefix;
    }

    public void setServerName(String serverName) {
        this.serverName = serverName;
    }

    @Override
    public boolean isConnected() {
        return isConnected;
    }
}
